/**
 * Project Name:Micro-Services-RPC-Registry
 * File Name   :MultiCuratorClientFactory.java
 * Package Name:com.micro.services.rpc.registry.support
 * Date:2015年9月7日下午11:56:22
 * Copyright (c) 2015, http://my.oschina.net/httpssl All Rights Reserved.
 *
*/

package com.micro.services.rpc.registry.support;

import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.lang3.StringUtils;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.utils.CloseableUtils;

import com.micro.services.rpc.registry.support.ClientCuratorFactory;

/**
 * ClassName:MultiCuratorClientFactory <br/>
 * Function :TODO ADD FUNCTION. <br/>
 * Reason	:TODO ADD REASON. <br/>
 * Date     :2015年9月7日 下午11:56:22 <br/>
 * @author  :http://my.oschina.net/httpssl
 * @email   :491835898@QQ.COM
 * @since   :JDK 1.7
 * @see 	 
 */
public class MultiCuratorClientFactory implements ClientCuratorFactory{
	// 注册中心获取过程锁
	private final ReentrantLock LOCK = new ReentrantLock();
	/**
	 * 根据一个AppName,缓存一个CuratorFramework客户端
	 */
	private static volatile Map<String, CuratorFramework> KV_APP_CURATORFRAMEWORK = new ConcurrentHashMap<String, CuratorFramework>();

	@Override
	public Collection<String> getAppNames() {
		return Collections.unmodifiableCollection(KV_APP_CURATORFRAMEWORK.keySet());
	}

	@Override
	public boolean isContainsApp(String appName) {
		return KV_APP_CURATORFRAMEWORK.containsKey(appName);
	}

	@Override
	public CuratorFramework getCuratorFrameworkByAppName(String appName) {
		return KV_APP_CURATORFRAMEWORK.get(appName);
	}

	@Override
	public boolean installCuratorFramework(String appName, CuratorFramework curatorFramework) {
		LOCK.tryLock();
		try {
			if (StringUtils.isBlank(appName) || curatorFramework == null) {
				throw new IllegalArgumentException("install param is bad!");
			}
			if (curatorFramework.getState() != CuratorFrameworkState.STARTED) {
				throw new IllegalArgumentException("please waite the CuratorFramework be [started]!");
			}
			KV_APP_CURATORFRAMEWORK.put(appName, curatorFramework);
		} finally {
			LOCK.unlock();
		}
		return true;
	}

	@Override
	public boolean uninstallCuratorFramework(String appName, CuratorFramework curatorFramework) {
		LOCK.tryLock();
		try {
			if(isContainsApp(appName)){
				try {
					if(curatorFramework!=null)
						CloseableUtils.closeQuietly(curatorFramework);
				} catch (Exception e) {
				}finally {
					curatorFramework = null;
				}
				KV_APP_CURATORFRAMEWORK.remove(appName);
			}
		} finally {
			LOCK.unlock();
		}
		return true;
	}
	/**
	 * 根据应用卸载 CuratorFramework
	 */
	@Override
	public boolean uninstallCuratorFramework(String appName) {
		uninstallCuratorFramework(appName,null);
		return true;
	}
}